<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row class="row_btn">
        <el-col>
          <el-button
            type="primary"
            @click="addRolesDialogVisible=true"
          >添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 展示的表格 -->
      <el-table
        :data="rolesList"
        border
        stripe
      >
        <el-table-column
          type="expand"
          label="#"
        >
          <template slot-scope="scope">
            <el-row
              v-for="(item1, l1) in scope.row.children"
              :key="item1.id"
              :class="['line_bottom', l1===0? 'line_top':'', 'v_center']"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="closeTagById(scope.row, item1.id)"
                >
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级权限 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2, l2) in item1.children"
                  :key="item2.id"
                  :class="[l2===0 ? '':'line_top', 'v_center']"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="closeTagById(scope.row, item2.id)"
                    >
                      {{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="closeTagById(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column
          type="index"
          label="编号"
          width="80px"
        >
        </el-table-column>
        <el-table-column
          prop="roleName"
          label="角色名称"
        >
        </el-table-column>
        <el-table-column
          prop="roleDesc"
          label="角色描述"
        >
        </el-table-column>
        <el-table-column label="操作">
          <!-- 添加三个按钮 -->
          <!-- 修改角色信息 -->
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除角色信息 -->
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              slot="reference"
              @click="removeRolesById(scope.row.id)"
            ></el-button>
            <!-- 设置角色权限 -->
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-setting"
              @click="showRightsDialog(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色的 Dialog -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRolesDialogVisible"
      width="50%"
      center
      @close="addRolesClose"
    >
      <span>
        <el-form
          label-width="80px"
          :model="addRolesForm"
          :rules="addRolesRules"
          ref="addRolesFormRef"
        >
          <el-form-item
            label="角色名称"
            prop="roleName"
          >
            <el-input v-model="addRolesForm.roleName"></el-input>
          </el-form-item>
          <el-form-item
            label="角色描述"
            prop="roleDesc"
          >
            <el-input v-model="addRolesForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="addRolesDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="postAddRolesForm"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改角色的 Dialog -->
    <el-dialog
      title="修改角色"
      :visible.sync="editRolesDialogVisible"
      width="50%"
      center
      @close="editRolesClose"
    >
      <span>
        <el-form
          label-width="80px"
          :model="editRolesForm"
          :rules="addRolesRules"
          ref="editRolesFormRef"
        >
          <el-form-item
            label="角色名称"
            prop="roleName"
          >
            <el-input v-model="editRolesForm.roleName"></el-input>
          </el-form-item>
          <el-form-item
            label="角色描述"
            prop="roleDesc"
          >
            <el-input v-model="editRolesForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="editRolesDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="postEditRolesForm()"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!-- 设置角色权限的 Dialog -->
    <el-dialog
      title="设置权限"
      :visible.sync="setRolesDialogVisible"
      width="50%"
      center
      @close="setRolesDialogCloed"
    >
      <!-- 树形控件 -->
      <el-tree
        :data="rightsList"
        :props="treeProps"
        ref="treeRef"
        show-checkbox
        node-key="id"
        :default-expand-all="true"
        :default-checked-keys="defKeys"
      ></el-tree>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="setRolesDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="postSetRights"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    var validateRoleName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入角色名称'))
      } else {
        callback()
      }
    }
    var validateRoleDesc = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入角色描述'))
      } else {
        callback()
      }
    }
    return {
      // 当前要分配角色的id
      roleId: '',
      rolesList: [],
      rightsList: [],
      addRolesForm: {
        roleName: '',
        roleDesc: ''
      },
      editRolesForm: {
        roleId: '',
        roleName: '',
        roleDesc: ''
      },
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      defKeys: [],
      addRolesRules: {
        roleName: [
          { required: true, validator: validateRoleName, trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, validator: validateRoleDesc, trigger: 'blur' }
        ]
      },
      addRolesDialogVisible: false,
      editRolesDialogVisible: false,
      setRolesDialogVisible: false
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        this.$message.error('获取用户角色失败!')
      }
      this.rolesList = res.data
    },
    addRolesClose () {
      this.$refs.addRolesFormRef.resetFields()
    },
    postAddRolesForm () {
      // 先进行预校验
      this.$refs.addRolesFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请填写完整的信息!')
        }
        // 发起添加用户角色请求
        const { data: res } = await this.$http.post('roles', this.addRolesForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色失败!')
        }
        this.$message.success('添加角色成功!')
        this.getRolesList()
        this.addRolesDialogVisible = false
      })
    },
    editRolesClose () {
      this.$refs.editRolesFormRef.resetFields()
    },
    postEditRolesForm () {
      // 预校验数据
      this.$refs.editRolesFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请填写完整的信息!')
        }
        const { data: res } = await this.$http.put(`roles/${this.editRolesForm.roleId}`, { roleName: this.editRolesForm.roleName, roleDesc: this.editRolesForm.roleDesc })
        if (res.meta.status !== 200) {
          return this.$message.error('修改用户角色失败!')
        }
        this.editRolesClose()
        this.editRolesDialogVisible = false
        this.$message.success('修改用户角色成功!')
        this.getRolesList()
      })
    },
    showEditDialog (roleId) {
      this.editRolesDialogVisible = true
      this.editRolesForm.roleId = roleId
    },
    async removeRolesById (roleId) {
      const confirmInfo = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
      if (confirmInfo === 'confirm') {
        this.$http.delete('roles/' + roleId)
        this.getRolesList()
        this.$message.success('删除角色成功!')
      }
    },
    async closeTagById (role, rightId) {
      const confirmInfo = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
      if (confirmInfo === 'confirm') {
        const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
        if (res.meta.status !== 200) {
          return this.$message.error('取消权限失败!')
        }
        role.children = res.data
        this.$message.success('取消权限成功!')
      }
    },
    async showRightsDialog (role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败!')
      }
      this.rightsList = res.data
      // 递归拿到三级节点id
      this.getLeafKeys(role, this.defKeys)
      this.setRolesDialogVisible = true
    },
    // 通过递归 获得三级节点id，保存到defKeys中
    getLeafKeys (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }

      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    setRolesDialogCloed () {
      this.defKeys = []
      this.setRolesDialogVisible = false
    },
    async postSetRights () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]

      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) {
        return this.$message.error('更新失败!')
      }
      this.getRolesList()
      this.$message.success('更新成功!')
      this.setRolesDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-breadcrumb {
  padding: 15px;
}
.el-tag {
  margin: 7px;
}
.row_btn {
  padding: 15px;
}
.line_bottom {
  border-bottom: 1px solid #eeeeee;
}
.line_top {
  border-top: 1px solid #eeeeee;
}
.v_center {
  display: flex;
  align-items: center;
}
</style>
